﻿using Basic.FlowApplication.Interface;
using Basic.FlowCollect;
using Basic.FlowModel.Node;
using Basic.FlowModel.NodeRoute;
using Basic.FlowRemoteModel;
using Basic.FlowRemoteModel.Application.Model;
using Basic.FlowRemoteModel.FlowNode.Model;
using WeDonekRpc.Client;
using WeDonekRpc.Helper;

namespace Basic.FlowApplication.lmpl
{
    internal class FlowNodeStateService : IFlowNodeStateService
    {
        private readonly IFlowNodeCollect _Service;
        private readonly INodeRouteCollect _Route;
        private readonly IFlowAuditNodeStateCollect _NodeState;
        private readonly INodeAuditEmpCollect _AuditEmp;

        public FlowNodeStateService ( IFlowNodeCollect service,
            INodeRouteCollect route,
            IFlowAuditNodeStateCollect nodeState,
            INodeAuditEmpCollect auditEmp )
        {
            this._Service = service;
            this._Route = route;
            this._NodeState = nodeState;
            this._AuditEmp = auditEmp;
        }

        public FlowNodeState[] GetNodes ( long logId, long flowId )
        {
            NodeBase[] list = this._Service.Gets<NodeBase>(flowId);
            if ( list.IsNull() )
            {
                return Array.Empty<FlowNodeState>();
            }
            Dictionary<long, FlowNodeAuditStatus> state = this._NodeState.GetNodeStatus(logId);
            FlowNodeState[] nodes = list.ConvertMap<NodeBase, FlowNodeState>();
            RouteBase[] routes = this._Route.Gets<RouteBase>(flowId);
            Dictionary<long, string> show = this._AuditEmp.GetShow(flowId);
            nodes.ForEach(c =>
            {
                c.Show = show.GetValueOrDefault(c.Id);
                c.Status = state[c.Id];
                if ( !routes.IsNull() )
                {
                    c.ToNode = routes.Convert(a => a.NodeId == c.Id, a => new FlowToNode
                    {
                        NodeId = a.ToNodeId,
                        Id = a.Id,
                    });
                }
            });
            return nodes;
        }
    }
}
